package com.example.dp886;


import static com.example.dp886.constants.Constants.PROVINCE_URL;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.dp886.databinding.ChooseAreaBinding;
import com.example.dp886.dt.City;
import com.example.dp886.dt.County;
import com.example.dp886.dt.Province;
import com.example.dp886.util.HttpUtil;
import com.example.dp886.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";
    ChooseAreaBinding binding;

    public static final int LEVEL_PROVICE=0;//省级
    public static final int LEVEL_CITY=1;//市级
    public static final int LEVEL_COUNTY=2;//县级
    private int currentLevel= LEVEL_PROVICE;//省级列表

    List<Province> provinceList;//省的数据合集
    List<City> cityList;
    List<County> countyList;

    private Province selectedProvince;
    private City selectedCity;

    List<String> dataList = new ArrayList<>();//存省市县的列表
    ArrayAdapter<String> adapter;

    ProgressDialog progressDialog;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding= ChooseAreaBinding.inflate(inflater,container,false);

        adapter=new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1,dataList);


        binding.listView.setAdapter(adapter);



        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //绑定列表项的点击事件
        binding.listView.setOnItemClickListener((adapterView, view, position, id) -> {
            if(currentLevel==LEVEL_PROVICE){
                selectedProvince=provinceList.get(position);
                queryCities();
            }else if (currentLevel==LEVEL_CITY){
                selectedCity=cityList.get(position);
                queryCounties();
            }else if (currentLevel==LEVEL_COUNTY){
 //               County county = countyList.get(position);
 //               String spot=String.format("%s|%s|%s",
 //               selectedProvince.getProvinceName(),
//                selectedCity.getCityName(),
//                county.getCountyName());
//                String location= county.getWeatherId().substring(2);
//                Log.d("test", "onActivityCreated: "+spot+"|"+location);

//                Intent intent=new Intent(getActivity(),WeatherActivity.class);
//                intent.putExtra("spot",spot);
//                intent.putExtra("location",location);
//                startActivity(intent);
 //               getActivity().finish();


            }
        });
        binding.backButton.setOnClickListener(v -> {
            if (currentLevel==LEVEL_CITY){
                queryProvinces();
            }else if (currentLevel==LEVEL_COUNTY){
                queryCities();
            }
        });

        queryProvinces();//查寻省份

    }

    private void queryCounties() {
        binding.titleText.setText(selectedProvince.getProvinceName()+":"+selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);

        countyList= LitePal.where("cityId=?",
                String.valueOf(selectedCity.getId())).find(County.class);
        if(countyList.size()>0){
            dataList.clear();
            countyList.forEach(item->{
                dataList.add(item.getCountyName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_COUNTY;
        }else {
            //数据表是空的从网络获取数据
            String url=PROVINCE_URL+"/"+selectedProvince.getProvinceCode()+"/"+selectedCity.getCityCode();
            queryFromServer(url, COUNTY);
        }
    }

    private void queryCities() {
        binding.titleText.setText(selectedProvince.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);

        cityList= LitePal.where("provinceId=?",
                String.valueOf(selectedProvince.getId())).find(City.class);
        if(cityList.size()>0){
            dataList.clear();
            cityList.forEach(item->{
                dataList.add(item.getCityName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_CITY;
        }else {
            //数据表是空的从网络获取数据
            String url=PROVINCE_URL+"/"+selectedProvince.getProvinceCode();
            queryFromServer(url, CITY);
        }
    }

    private void queryProvinces(){

        //尝试从本地数据库中访问省份表，尝试获取省份列表数据

        binding.titleText.setText("中国(China)");
        binding.backButton.setVisibility(View.GONE);

        provinceList= LitePal.findAll(Province.class);
        if(provinceList.size()>0){
            dataList.clear();
            provinceList.forEach(item->{
                dataList.add(item.getProvinceName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel=LEVEL_PROVICE;
        }else {
            //数据表是空的从网络获取数据
            queryFromServer(PROVINCE_URL, PROVINCE);
        }
    }

    private void queryFromServer(String url, String type) {
        Log.d("test", url);
        showProgressDialog();//显示加载进度条
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(()->{
                    Toast.makeText(getActivity(),"访问网络失败!",Toast.LENGTH_SHORT).show();
                    closeProgressDialog();
                });

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson = response.body().string();
                Log.d("test", "onResponse: "+strJson);
                boolean result= false;
                if(PROVINCE.equals(type)){
                    try {
                        result= Utility.handleProvinceResponce(strJson);//写入数据
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else if (CITY.equals(type)){
                    result = Utility.handleCityResponce(strJson,selectedProvince.getId());
                }else if (COUNTY.equals(type)){
                    result = Utility.handleCountyResponce(strJson,selectedCity.getId());
                }
                if (result){
                    if (PROVINCE.equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryProvinces();
                        });
                    }else if(CITY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCities();
                        });
                    }else if(COUNTY.equals(type)){
                        getActivity().runOnUiThread(()->{
                            queryCounties();
                        });
                    }
                    closeProgressDialog();
                }else{
                    getActivity().runOnUiThread(()->{
                        Toast.makeText(getContext(),
                                "数据解析失败",Toast.LENGTH_SHORT).show();
                        closeProgressDialog();

                    });
                }
            }
        });
    }

    private void closeProgressDialog() {
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        if(progressDialog==null){
            //创建对话框
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在访问网络请稍后！！！");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }
}
